package com.tanhua.manage.service;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.manage.mapper.LogMapper;
import com.tanhua.manage.mapper.UserInfoMapper;
import com.tanhua.manage.mapper.UserMapper;
import com.tanhua.manage.pojo.Log;
import com.tanhua.manage.pojo.User;
import com.tanhua.manage.pojo.UserInfo;
import com.tanhua.manage.vo.PageResult;
import com.tanhua.manage.vo.UserVo;
import com.tanhua.manage.vo.UsersVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
@Service
public class UsersService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;
    @Autowired
    private UserInfoService userInfoService;
    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;
    @Autowired
    private UserService userService;
    @Autowired
    private LogMapper logMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private UserMapper userMapper;


    /**
     * 用户数据翻页
     *
     * @param page 当前页码
     * @param pageSize  页码大小
     * @param id  用户Id
     * @param nickName  昵称
     * @param city 城市
     * @return
     */
    public PageResult queryUsersList(Integer page, Integer pageSize, Long id, String nickName, String city) {
        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);


        //2.得到MongoDB的数据  拿到了所有上次更新的时间
        List<UserLocationVo> userLocationList = this.userLocationApi.queryByAllUserLocation();

        if(userLocationList==null){
            return pageResult;
        }
        //去拿到数据库的所有信息 收集Id
        Set<Long> userIds = new HashSet<>();
        try {
            userIds = userLocationList.stream().map(UserLocationVo::getUserId).collect(Collectors.toSet());
        }catch (Exception e){
            e.printStackTrace();
        }


        QueryWrapper<UserInfo> queryWrapper1 = new QueryWrapper<>();

        //设置查询条件
        queryWrapper1.in("user_id", userIds);
        if (StringUtils.isNotEmpty(nickName)){
            queryWrapper1.like("nick_name", nickName);
        }
        if(StringUtils.isNotEmpty(city)){
            queryWrapper1.like("city", city);
        }
        Page<UserInfo> infoPage = new Page<>(page,pageSize);
        IPage<UserInfo> infoIPage = this.userInfoMapper.selectPage(infoPage, queryWrapper1);
        pageResult.setCounts((int) infoIPage.getTotal());
        pageResult.setPages((int) infoIPage.getCurrent());
        List<UserInfo> userInfoList = infoIPage.getRecords();
        //查询Mysql得到另一张表User得到手机号
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id", userIds);
        List<User> userList = this.userService.queryUserByIds(userQueryWrapper);

        //查询最近活跃时间
        QueryWrapper<Log> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id",userIds);
        List<Log> logList = this.logMapper.selectList(queryWrapper);
        List<UsersVo> userBasicVolist = new ArrayList<>();

        if(id ==null){
            for (UserLocationVo userLocationVo : userLocationList) {
                for (UserInfo userInfo : userInfoList) {
                    if (userLocationVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                        UsersVo userBasicVo = new UsersVo();
                        userBasicVo.setId(Integer.valueOf(userInfo.getUserId().toString()));
                        userBasicVo.setLogo(userInfo.getLogo());
                        userBasicVo.setLogoStatus("1"); //填充数据
                        userBasicVo.setNickname(userInfo.getNickName());
                        //userBasicVo.setMobile();
                        userBasicVo.setSex(userInfo.getSex().toString());
                        userBasicVo.setAge(userInfo.getAge());
                        userBasicVo.setOccupation(userInfo.getIndustry());
                        userBasicVo.setLastActiveTime(userLocationVo.getLastUpdated());
                        userBasicVo.setCity(userInfo.getCity());
                        //userLocationVo.getLastUpdated().intValue()
                        userBasicVolist.add(userBasicVo);
                        break;
                    }
                }
            }
        /*for (UsersVo userBasicVo : userBasicVolist) {
            for (Log log:logList){
                if (userBasicVo.getId().longValue()==log.getUserId().longValue()){
                    userBasicVo.setLastActiveTime(log.getActiveTime().getTime());
                    break;
                }
            }
        }*/

            for (UsersVo userBasicVo : userBasicVolist) {
                for (User user : userList) {
                    if (userBasicVo.getId().longValue() == user.getId().longValue()) {
                        userBasicVo.setMobile(user.getMobile());
                        userBasicVo.setUserStatus(user.getFrozenTime()==0?"1":"2");
                        break;
                    }
                }
            }

        }
            else {
            List<UserInfo> records = infoIPage.getRecords();

            for (UserLocationVo userLocationVo : userLocationList) {
                for (UserInfo userInfo : records) {
                    if (userInfo.getUserId() == id &&
                            userLocationVo.getUserId() == id) {

                        UsersVo userBasicVo = new UsersVo();

                        userBasicVo.setId(Integer.valueOf(userInfo.getUserId().toString()));
                        userBasicVo.setLogo(userInfo.getLogo());
                        userBasicVo.setLogoStatus("1"); //填充数据
                        userBasicVo.setNickname(userInfo.getNickName());
                        //userBasicVo.setMobile();
                        userBasicVo.setSex(userInfo.getSex().toString());
                        userBasicVo.setAge(userInfo.getAge());
                        userBasicVo.setOccupation(userInfo.getIndustry());
                        userBasicVo.setLastActiveTime(userLocationVo.getLastUpdated());
                        userBasicVo.setCity(userInfo.getCity());
                        //userLocationVo.getLastUpdated().intValue()
                        userBasicVolist.add(userBasicVo);
                        break;
                    }
                }
            }
        /*for (UsersVo userBasicVo : userBasicVolist) {
            for (Log log:logList){
                if (userBasicVo.getId().longValue()==log.getUserId().longValue()){
                    userBasicVo.setLastActiveTime(log.getActiveTime().getTime());
                    break;
                }
            }
        }*/



            for (UsersVo userBasicVo : userBasicVolist) {
                for (User user : userList) {
                    if (userBasicVo.getId().longValue() == user.getId().longValue()) {
                        userBasicVo.setMobile(user.getMobile());
                        //查询redis
                        String redisFreezeKey = "Freezing_" + user.getId();
                        if (this.redisTemplate.hasKey(redisFreezeKey)){//冻结状态
                            userBasicVo.setUserStatus("2");
                        }else {//redis过期
                            //帮他解冻
                            LambdaUpdateWrapper<User> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                            lambdaUpdateWrapper
                                    .eq(com.tanhua.manage.pojo.User::getId, user.getId()) //修改的userId
                                    .set(com.tanhua.manage.pojo.User::getUpdated, new Date()) //更新修改时间
                                    .set(com.tanhua.manage.pojo.User::getFrozenTime, 0)//置空冻结状态种种
                                    .set(com.tanhua.manage.pojo.User::getFrozenRange, 0)
                                    .set(com.tanhua.manage.pojo.User::getFrozenReason, null)
                                    .set(com.tanhua.manage.pojo.User::getFrozenRemark, null)
                                    .set(com.tanhua.manage.pojo.User::getThawedReason, "冻结过期了"); //添加解冻状态
                            userMapper.update(null, lambdaUpdateWrapper);
                            userBasicVo.setUserStatus("1");
                        }

                        userBasicVo.setUserStatus(user.getFrozenTime()==0?"1":"2");
                        break;
                    }
                }
            }

        }

        //7.将数据填入返回的Vo
        pageResult.setItems(userBasicVolist);
        return pageResult;
}
        /**
         * 用户基本资料
         * @param userId
         * @return
         */
        public UserVo queryUsers (Long userId){
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            UserInfo userInfo = this.userInfoMapper.selectOne(queryWrapper);
            if (userInfo == null) {
                return null;
            }
            UserVo userVo = new UserVo();
            userVo.setAge(userInfo.getAge());
            userVo.setCity(userInfo.getCity());
            userVo.setCreated(userInfo.getCreated().toString());
            userVo.setId(userInfo.getUserId().intValue());
            userVo.setLogo(userInfo.getLogo());
            userVo.setNickname(userInfo.getNickName());
            userVo.setSex(userInfo.getSex().getValue() == 1 ? "男" : "女");
            userVo.setTags(userInfo.getTags());
            userVo.setPersonalSignature(userInfo.getPersonalSignature());
            Long likeCount = this.userLikeApi.queryLikeCount(userId); //喜欢数
            Long fanCount = this.userLikeApi.queryFanCount(userId); //粉丝数
            userVo.setCountLiked(likeCount.intValue());
            userVo.setCountBeLiked(fanCount.intValue());
            userVo.setIncome(Integer.valueOf(userInfo.getIncome()));
          //查询手机号
           User user = this.userService.queryUserById(userId);
            userVo.setMobile(user.getMobile());
            //查询最近活跃地
            UserLocationVo userLocationVo = this.userLocationApi.queryByUserId(userId);
            /*Log log = this.logMapper.selectById(userId);*/

            userVo.setLastActiveTime(userLocationVo.getLastUpdated());
             //最近活跃地
            userVo.setLastLoginLocation(userLocationVo.getAddress());
            //用户状态

            userVo.setUserStatus(user.getFrozenTime()==0?"1":"2");
            //配对人数
            userVo.setCountMatching(new Random().nextInt(10+1));
            return userVo;
        }
    }




